package com.bubblegumproject.ogo.component;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.log4j.Logger;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * This class enforces the Component system on a per-instance basis. 
 *
 * @author Azubuko Obele (buko.obele@gmail.com)
 */
public class ComponentInstanceProxy implements ComponentInstance, MethodInterceptor {

    private ComponentProxy typeProxy;

    private List<Object> dependencySequence = new ArrayList<Object>();

    private static final Logger log = Logger.getLogger(ComponentInstanceProxy.class);

    public ComponentInstanceProxy(ComponentProxy proxy) {
        this.typeProxy = proxy;
    }

    public Object intercept(Object object, Method method, Object[] arguments, MethodProxy methodProxy)
            throws Throwable {
        if (isComponentInstanceMethod(method)) {
            return method.invoke(this, arguments);
        } else {
            return typeProxy.intercept(object, method,  arguments, methodProxy);
        }
    }

    private boolean isComponentInstanceMethod(Method method) {
        return (method.getName().equals("addDependency") || method.getName().equals("getDependencySequence"));
    }

    public void addDependency(Object component) {
        assert(component != null);
        dependencySequence.add(component);
    }

    public List<Object> getDependencySequence() {
        return dependencySequence;
    }
}
